package com.xianniu.ltc.controller;

import cn.devezhao.bizz.security.member.Member;
import cn.devezhao.commons.web.ServletUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.rebuild.api.RespBody;
import com.rebuild.core.Application;
import com.rebuild.core.UserContextHolder;
import com.rebuild.core.privileges.UserHelper;
import com.rebuild.core.privileges.bizz.User;
import com.rebuild.utils.JSONUtils;
import com.rebuild.web.BaseController;
import com.rebuild.web.InvalidParameterException;
import com.rebuild.web.user.signup.LoginController;
import com.xianniu.ltc.feign.api.ThirdPartyService;
import com.xianniu.ltc.mapper.TRoleMapper;
import com.xianniu.ltc.model.po.QccFuzzySearchPO;
import com.xianniu.ltc.service.TRoleService;
import com.xianniu.ltc.util.GetEnterpriseUtil;
import com.xxl.sso.core.entity.ReturnT;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author WangRuiJie
 * @Title: CommonSearchController
 * @Package com.xianniu.ltc.controller
 * @Description: 公共查询方法类
 * @date 2021/6/154:47 下午
 */
@RestController
@Slf4j
@RequestMapping(value = "/commonSearch")
public class CommonSearchController extends BaseController {

    @Autowired
    private TRoleService roleService;
    @Resource
    private GetEnterpriseUtil util;

    @GetMapping("/department")
    public JSON loadDepartment(HttpServletRequest request) {
        final String query = request.getParameter("q");
        String tenantCode = (String) ServletUtils.getSessionAttribute(request, LoginController.TENANT_CODE);

        Member[] members= Application.getUserStore().getAllDepartments(tenantCode);
        // 排序
        members = UserHelper.sortMembers(members);
        JSONArray found = new JSONArray();
        for (Member m : members) {
            if (m.isDisabled()) continue;

            String name = m.getName();

            final User ifUser = m instanceof User ? (User) m : null;
            if (ifUser != null) {
                if (!ifUser.isActive()) continue;
                name = ifUser.getFullName();
            }

            if (StringUtils.isBlank(query)
                    || StringUtils.containsIgnoreCase(name, query)
                    || (ifUser != null && StringUtils.containsIgnoreCase(ifUser.getName(), query))
                    || (ifUser != null && ifUser.getEmail() != null && StringUtils.containsIgnoreCase(ifUser.getEmail(), query))) {
                JSONObject o = JSONUtils.toJSONObject(new String[]{"id", "text"},
                        new String[]{m.getIdentity().toString(), name});
                found.add(o);

                // 最多显示40个
                if (found.size() >= 40) break;
            }
        }
        return found;
    }

    @GetMapping("/users")
    public JSON loadUsers(HttpServletRequest request) {
        final String dept = request.getParameter("dept");
        final String query = request.getParameter("q");
        String tenantCode = (String) ServletUtils.getSessionAttribute(request, LoginController.TENANT_CODE);

        Member[] members= Application.getUserStore().getAllUsers(tenantCode);
        // 排序
        members = UserHelper.sortMembers(members);
        JSONArray found = new JSONArray();
        for (Member m : members) {
            if (m.isDisabled()) continue;

            String name = m.getName();

            final User ifUser = m instanceof User ? (User) m : null;
            if (ifUser != null) {
                if (!ifUser.isActive()) continue;
                // 查询不是选择部门的用户则跳过
                if (!ifUser.getOwningDept().getIdentity().toString().equals(dept)) continue;
                name = ifUser.getFullName();
            }

            if (StringUtils.isBlank(query)
                    || StringUtils.containsIgnoreCase(name, query)
                    || (ifUser != null && StringUtils.containsIgnoreCase(ifUser.getName(), query))
                    || (ifUser != null && ifUser.getEmail() != null && StringUtils.containsIgnoreCase(ifUser.getEmail(), query))) {
                JSONObject o = JSONUtils.toJSONObject(new String[]{"id", "text"},
                        new String[]{m.getIdentity().toString(), name});
                found.add(o);

                // 最多显示40个
                if (found.size() >= 40) break;
            }
        }
        return found;
    }

    @GetMapping("/selectRoleList")
    public ReturnT selectRoleList(String name, HttpServletRequest request){
        String tenantCode = (String) ServletUtils.getSessionAttribute(request, LoginController.TENANT_CODE);
        UserContextHolder.setTenant(tenantCode);
        return roleService.selectRoleList(name);
    }

    @PostMapping("/checkEnterprise")
    public JSONAware checkEnterprise(@RequestBody QccFuzzySearchPO po){
        if (StringUtils.isBlank(po.getKey())){
            return null;
        }
        // 1，校验企业名称在当前企业中是否存在
        Object[] o = Application.createQueryNoFilter(
                "select qiyexinxiId from qiyexinxi where qiyexinxiName = ? and tenantCode = ?")
                .setParameter(1, po.getKey())
                .setParameter(2, UserContextHolder.getTenant())
                .unique();
        if (o != null) {
            return RespBody.errorl("企业信息已存在");
        }
        // 2，根据企业名称调用三方查询模糊匹配的企业信息列表
        return util.fuzzySearch(po);
    }
}
